package com.restaurant.web.android.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.restaurant.domain.Tableorder;
import com.restaurant.proxies.Order;
import com.restaurant.service.MenuorderService;
import com.restaurant.service.TableorderService;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

@Component
@RequestMapping("/orderservice.do")
public class OrderController {
	
	@Autowired
	private TableorderService objTableorderService;
	
	@Autowired
	private MenuorderService objMenuorderService;
	
	@RequestMapping(method=RequestMethod.POST)
	public void orderControllerPOSTRequest(HttpServletRequest request, HttpServletResponse response){
		XStream objXStream = new XStream(new DomDriver());
		objXStream.alias("Order", Order.class);
		objXStream.alias("List", List.class);
		
		Boolean openedOrClosedOrder = (Boolean) objXStream.fromXML(request.getParameter("Boolean"));
		
		List<Order> listOrders = new ArrayList<Order>();
		List<Tableorder> listTableorders = null;
		try {
			listTableorders = objTableorderService.loadByHql("From Tableorder t WHERE t.isended = " + openedOrClosedOrder.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		Order order = null;
		for(Tableorder tableorder : listTableorders){
			order = new Order();
			order.setTableorder(tableorder);
			order.setAmount(objMenuorderService.getSumMenuPrice(tableorder.getTableorderID()));
			listOrders.add(order);
		}
		
		try {
			response.getWriter().print(objXStream.toXML(listOrders));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
